package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import sun.misc.BASE64Encoder;

public class MailSender {

	private String smtpServer = "smtp.qq.com";
	private int port = 25;
	
	public static void main(String[] args) {
		Message msg = new Message("334074758@qq.com", "zjh92119@gmail.com", "hello", "I miss you so much!");
		new MailSender().sendMail(msg);
	}
	
	public void sendMail(Message msg){
		Socket socket = null;
		try{
			String username = "334074758";
			String password = "17888668vv===zjh";
			username = new BASE64Encoder().encode(username.getBytes());
			password = new BASE64Encoder().encode(password.getBytes());
			
			socket = new Socket(smtpServer, port);
			BufferedReader br = getReader(socket);
			PrintWriter pw = getWriter(socket);
			String localhost = InetAddress.getLocalHost().getHostName();
			
			sendAndRecieve(null, br, pw);
			sendAndRecieve("HELO " + username, br, pw);
			sendAndRecieve("AUTH LOGIN", br, pw);
			sendAndRecieve(username, br, pw);
			sendAndRecieve(password, br, pw);
			sendAndRecieve("MAIL FROM:<" + msg.from + ">", br, pw);
			sendAndRecieve("RCPT TO:<" + msg.to + ">", br, pw);
			sendAndRecieve("DATA", br, pw);
			pw.println(msg.data);
			System.out.println("Client >" + msg.data);
			sendAndRecieve(".", br, pw);
			sendAndRecieve("QUIT", br, pw);
		}catch(IOException ioe){
			ioe.printStackTrace();
		}finally{
			try{
				if(socket != null)	socket.close();
			}catch(IOException ioe){
				ioe.printStackTrace();
			}
		}
	}
	
	private void sendAndRecieve(String str, BufferedReader br, PrintWriter pw) 
			throws IOException{
		if(str != null){
			System.out.println("Client >" + str);
			pw.println(str);
			System.out.println(1);
		}
		System.out.println(2);
		String response;
		if((response = br.readLine()) != null){
			System.out.println("Server >" + response);
		}
		System.out.println(3);
	}
	
	private PrintWriter getWriter(Socket socket) throws IOException{
		OutputStream os = socket.getOutputStream();
		return new PrintWriter(os);
	}
	
	private BufferedReader getReader(Socket socket) throws IOException{
		InputStream is  = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(is));
	}
	
	static class Message{
		String from;
		String to;
		String subject;
		String content;
		String data;
		public Message(String from, String to, String subject, String content) {
			this.from 		= from;
			this.to   		= to;
			this.subject 	= subject;
			this.content 	= content;
			this.data		= "Subject:" + content + "\r\n" + content;
		}
	}
	
}
